<template>
  <view class="profile-container">
    <!-- 头部信息区域 -->
    <view class="header">
      <image class="avatar" :src="userInfo.avatar" mode="aspectFill"></image>
      <view class="user-info">
        <text class="username">{{ userInfo.username }}</text>
        <text class="birthday">{{ userInfo.birthday }}</text>
      </view>
      <image class="edit-icon" src="/static/icons/edit.png" mode="widthFix" @click="editProfile"></image>
    </view>

    <!-- 我的档案模块 -->
    <view class="module my-records">
      <text class="module-title">我的档案</text>
      <view class="module-content">
        <view class="record-item" @click="navigateTo('/pages/guahao/guahao')">
          <image src="/static/dan.png" mode="widthFix"></image>
          <text>挂号订单</text>
        </view>
        <view class="record-item" @click="navigateTo('history')">
          <image src="/static/bing.png" mode="widthFix"></image>
          <text>过往病史</text>
        </view>
      </view>
    </view>

    <!-- 个人健康数据模块 -->
    <view class="module health-data">
      <view class="module-header">
        <text class="module-title">个人健康数据</text>
        <text class="data-date">{{ healthData.update_time || '暂无数据' }}</text>
        <image class="edit-icon-small" src="/static/icons/edit.png" mode="widthFix" @click="editHealthData"></image>
      </view>
      
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <text>加载中...</text>
      </view>
      
      <!-- 数据展示 -->
      <view v-else-if="healthData.height" class="data-list">
        <view class="data-item">
          <text>身高（cm）</text>
          <text>{{ healthData.height }}</text>
        </view>
        <view class="data-item">
          <text>体重（kg）</text>
          <text>{{ healthData.weight }}</text>
        </view>
        <view class="data-item">
          <text>血压（mmHg）</text>
          <text>{{ healthData.blood_ressure }}</text>
        </view>
        <view class="data-item">
          <text>血糖（mmol/L）</text>
          <text>{{ healthData.blood_sugar }}</text>
        </view>
      </view>
      
      <!-- 空数据状态 -->
      <view v-else-if="!error" class="empty-container">
        <text>暂无健康数据</text>
        <button @click="fetchHealthData">添加数据</button>
      </view>
      
      <!-- 错误状态 -->
      <view v-else class="error-container">
        <text>{{ error }}</text>
        <button @click="fetchHealthData">重试</button>
      </view>
    </view>

    <!-- 功能列表模块 -->
    <view class="module function-list">
      <view class="function-item" v-for="item in functionList" :key="item.path" @click="navigateTo(item.path)">
        <image :src="item.icon" mode="widthFix"></image>
        <text>{{ item.label }}</text>
        <image class="arrow-icon" src="/static/qu.png" mode="widthFix"></image>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';

// 用户信息
const userInfo = ref({
  username: '加载中...',
  birthday: '',
  avatar: '/static/tou.png'
});

// 健康数据
const healthData = ref({
  height: '',
  weight: '',
  blood_ressure: '',
  blood_sugar: '',
  update_time: ''
});

// 加载状态
const loading = ref(true);
const error = ref('');

// 功能列表
const functionList = ref([
  { icon: '/static/dizhi.png', label: '地址管理', path: '/pages/Login/Login' },
  { icon: '/static/yisheng.png', label: '医生入驻', path: '/pages/Login/Login' },
  { icon: '/static/tuichu.png', label: '退出账号', path: '/pages/Login/Login' },
  { icon: '/static/guan.png', label: '关于', path: '/pages/Login/Login' }
]);

// 获取用户信息
const fetchUserInfo = () => {
  uni.request({
    url: 'https://api.example.com/user/info',
    method: 'GET',
    header: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${uni.getStorageSync('token')}`
    },
    success: (res: any) => {
      if (res.statusCode === 200 && res.data.code === 0) {
        userInfo.value = res.data.data;
      } else {
        error.value = res.data.message || '获取用户信息失败';
      }
    },
    fail: (err) => {
      error.value = err.errMsg || '网络请求失败';
    }
  });
};

// 获取健康数据（关键部分）
const fetchHealthData = () => {
  loading.value = true;
  error.value = '';
  
  uni.request({
    url: 'http://localhost:3020/user/health',
    method: 'GET',
    header: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${uni.getStorageSync('token')}`
    },
    success: (res: any) => {
		console.log(res.data.data[0],'健康数据')
      if (res.statusCode === 200 && res.data.code === 200) {
        healthData.value = res.data.data[0];
      } else {
        error.value = res.data.message || '获取健康数据失败';
      }
    },
    fail: (err) => {
      error.value = err.errMsg || '网络请求失败';
    },
    complete: () => {
      loading.value = false;
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  fetchUserInfo();
  fetchHealthData();
  	 // const token = uni.getStorageSync('token');
  	 // if (token) {
  	 //   const payload: { userId: number; name: string } = jwtDecode(token);
  	 //   console.log('用户 ID:', payload.userId); // 直接从 Payload 取数据
  	 // }
});

// 导航函数
const navigateTo = (path: string) => {
  uni.navigateTo({ url: path });
};

// 编辑个人资料
const editProfile = () => {
  uni.navigateTo({ url: '/pages/edit-profile' });
};

// 编辑健康数据
const editHealthData = () => {
  if (!healthData.value.height) {
    // 无数据时跳转到添加页面
    uni.navigateTo({ url: '/pages/add-health-data' });
  } else {
    // 有数据时跳转到编辑页面
    uni.navigateTo({ url: '/pages/edit-health-data' });
  }
};
</script>

<style scoped lang="scss">
.profile-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 16px;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    background-color: #fff;
    padding: 16px;
    border-radius: 8px;

    .avatar {
      width: 64px;
      height: 64px;
      border-radius: 50%;
      margin-right: 12px;
    }

    .user-info {
      flex: 1;

      .username {
        font-size: 18px;
        font-weight: bold;
        color: #333;
      }

      .birthday {
        font-size: 14px;
        color: #999;
        margin-top: 4px;
      }
    }

    .edit-icon {
      width: 24px;
      height: 24px;
    }
  }

  .module {
    background-color: #fff;
    border-radius: 8px;
    margin-top: 16px;
    padding: 16px;

    &.my-records {
      .module-title {
        font-size: 16px;
        font-weight: bold;
        color: #333;
        margin-bottom: 12px;
      }

      .module-content {
        display: flex;
        justify-content: space-around;

        .record-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          image {
            width: 40px;
            height: 40px;
            margin-bottom: 4px;
          }

          text {
            font-size: 14px;
            color: #666;
          }
        }
      }
    }

    &.health-data {
      .module-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .module-title {
          font-size: 16px;
          font-weight: bold;
          color: #333;
        }

        .data-date {
          font-size: 14px;
          color: #999;
        }

        .edit-icon-small {
          width: 20px;
          height: 20px;
        }
      }

      .data-list {
        .data-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          color: #666;
          margin-bottom: 8px;

          text:first-child {
            color: #999;
          }
        }
      }
    }

    &.function-list {
      .function-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 12px 0;
        border-bottom: 1px solid #f5f5f5;

        image {
          width: 22px;
          height: 22px;
          margin-right: 8px;
        }

        text {
          flex: 1;
          font-size: 14px;
          color: #333;
        }

        .arrow-icon {
          width: 16px;
          height: 16px;
          margin-left: 8px;
        }
      }
    }
  }
}
</style>